﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using Fcdbas.Core.Reflection;

namespace Fcdbas.Core.Collections
{
    /// <summary>
    /// 实现EntityObject对象的比较，通过主键的方式
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EntityObjectComparer<T> : EqualityComparer<T> where T : EntityObject
    {
        public override bool Equals(T x, T y)
        {
            TypeX type = TypeX.Create(x.GetType());
            bool bRes = false;
            var piList = type.Type.GetProperties().Where(p => p.PropertyType.IsPublic == true).ToList();
            foreach (System.Reflection.PropertyInfo pi in piList)
            {
                EdmScalarPropertyAttribute ed = pi.GetCustomAttribute<EdmScalarPropertyAttribute>(false);
                if (ed != null && ed.EntityKeyProperty)
                {
                    PropertyInfoX infoX = PropertyInfoX.Create(pi);
                    
                    PropertyInfoX infoY = PropertyInfoX.Create(y.GetType(),pi.Name);
                    if (infoX != null && infoY != null)
                    {
                        if (infoX.GetValue(x).ToString() == infoY.GetValue(y).ToString())
                            bRes = true;
                        else
                            return false;
                    }
                    else
                        return false;
                }
            }
            return bRes;
        }

        public override int GetHashCode(T obj)
        {
            return obj.GetHashCode();
        }
    }
}
